{% extends 'base.html' %}
{% load static %}

{% block title %}数据分析仪表板 - CFS Web System{% endblock %}

{% block page_type %}analytics-dashboard{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item active">数据分析</li>
{% endblock %}

{% block content %}
<!-- 概览统计 -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-primary">
                <i class="fas fa-file-alt"></i>
            </div>
            <div class="stat-content">
                <h3 id="total-files">-</h3>
                <p>总文件数</p>
                <small class="text-success" id="files-trend">+0% 较昨日</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-success">
                <i class="fas fa-tasks"></i>
            </div>
            <div class="stat-content">
                <h3 id="total-tasks">-</h3>
                <p>处理任务</p>
                <small class="text-success" id="tasks-trend">+0% 较昨日</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-info">
                <i class="fas fa-layer-group"></i>
            </div>
            <div class="stat-content">
                <h3 id="total-templates">-</h3>
                <p>活跃模板</p>
                <small class="text-info" id="templates-trend">+0% 较昨日</small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon bg-warning">
                <i class="fas fa-database"></i>
            </div>
            <div class="stat-content">
                <h3 id="storage-used">-</h3>
                <p>存储使用</p>
                <small class="text-warning" id="storage-trend">+0% 较昨日</small>
            </div>
        </div>
    </div>
</div>

<!-- 图表区域 -->
<div class="row mb-4">
    <!-- 文件类型分布 -->
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-pie me-2"></i>文件类型分布
                    </h6>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary" onclick="refreshChart('fileTypes')">
                            <i class="fas fa-sync"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary" onclick="exportChart('fileTypes')">
                            <i class="fas fa-download"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <canvas id="fileTypesChart" height="300"></canvas>
            </div>
        </div>
    </div>
    
    <!-- 任务状态分布 -->
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-donut me-2"></i>任务状态分布
                    </h6>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary" onclick="refreshChart('taskStatus')">
                            <i class="fas fa-sync"></i>
                        </button>
                        <button type="button" class="btn btn-outline-secondary" onclick="exportChart('taskStatus')">
                            <i class="fas fa-download"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <canvas id="taskStatusChart" height="300"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- 趋势分析 -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-chart-line me-2"></i>使用趋势分析
                    </h6>
                    <div class="d-flex gap-2">
                        <select class="form-select form-select-sm" id="trend-period" onchange="updateTrendChart()">
                            <option value="7">最近7天</option>
                            <option value="30" selected>最近30天</option>
                            <option value="90">最近90天</option>
                        </select>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-secondary" onclick="refreshChart('trends')">
                                <i class="fas fa-sync"></i>
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="exportChart('trends')">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <canvas id="trendsChart" height="120"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- 详细统计 -->
<div class="row mb-4">
    <!-- 模板使用统计 -->
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-layer-group me-2"></i>模板使用统计
                    </h6>
                    <button type="button" class="btn btn-outline-primary btn-sm" onclick="viewAllTemplates()">
                        查看全部
                    </button>
                </div>
            </div>
            <div class="card-body">
                <div id="template-stats" class="template-stats">
                    <!-- 模板统计将动态加载 -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- 性能指标 -->
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-tachometer-alt me-2"></i>性能指标
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-6">
                        <div class="metric-item">
                            <div class="metric-value" id="avg-processing-time">-</div>
                            <div class="metric-label">平均处理时间</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="metric-item">
                            <div class="metric-value" id="success-rate">-</div>
                            <div class="metric-label">成功率</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="metric-item">
                            <div class="metric-value" id="queue-length">-</div>
                            <div class="metric-label">队列长度</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="metric-item">
                            <div class="metric-value" id="active-workers">-</div>
                            <div class="metric-label">活跃进程</div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-3">
                    <canvas id="performanceChart" height="150"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 实时活动 -->
<div class="row mb-4">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h6 class="mb-0">
                        <i class="fas fa-clock me-2"></i>实时活动
                    </h6>
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" id="auto-refresh" checked>
                        <label class="form-check-label" for="auto-refresh">
                            自动刷新
                        </label>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="activity-feed" class="activity-feed">
                    <!-- 活动记录将动态加载 -->
                </div>
            </div>
        </div>
    </div>
    
    <!-- 系统状态 -->
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-server me-2"></i>系统状态
                </h6>
            </div>
            <div class="card-body">
                <div class="system-status">
                    <div class="status-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <span>CPU使用率</span>
                            <span id="cpu-usage" class="badge bg-success">-</span>
                        </div>
                        <div class="progress mt-1">
                            <div class="progress-bar bg-success" id="cpu-progress" style="width: 0%"></div>
                        </div>
                    </div>
                    
                    <div class="status-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <span>内存使用率</span>
                            <span id="memory-usage" class="badge bg-info">-</span>
                        </div>
                        <div class="progress mt-1">
                            <div class="progress-bar bg-info" id="memory-progress" style="width: 0%"></div>
                        </div>
                    </div>
                    
                    <div class="status-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <span>磁盘使用率</span>
                            <span id="disk-usage" class="badge bg-warning">-</span>
                        </div>
                        <div class="progress mt-1">
                            <div class="progress-bar bg-warning" id="disk-progress" style="width: 0%"></div>
                        </div>
                    </div>
                    
                    <div class="status-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <span>网络状态</span>
                            <span id="network-status" class="badge bg-success">正常</span>
                        </div>
                    </div>
                    
                    <div class="status-item">
                        <div class="d-flex justify-content-between align-items-center">
                            <span>数据库连接</span>
                            <span id="db-status" class="badge bg-success">正常</span>
                        </div>
                    </div>
                </div>
                
                <div class="mt-3">
                    <div class="d-grid gap-2">
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="viewSystemLogs()">
                            <i class="fas fa-list"></i> 数据库日志
                        </button>
                        <button type="button" class="btn btn-outline-info btn-sm" onclick="viewFileLogs()">
                            <i class="fas fa-file-alt"></i> 文件日志
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 快速操作 -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <button type="button" class="btn btn-outline-primary w-100" onclick="exportReport()">
                            <i class="fas fa-file-export"></i><br>
                            <small>导出报告</small>
                        </button>
                    </div>
                    <div class="col-md-3">
                        <button type="button" class="btn btn-outline-success w-100" onclick="scheduleReport()">
                            <i class="fas fa-calendar-plus"></i><br>
                            <small>定时报告</small>
                        </button>
                    </div>
                    <div class="col-md-3">
                        <button type="button" class="btn btn-outline-info w-100" onclick="customAnalysis()">
                            <i class="fas fa-chart-bar"></i><br>
                            <small>自定义分析</small>
                        </button>
                    </div>
                    <div class="col-md-3">
                        <button type="button" class="btn btn-outline-warning w-100" onclick="systemMaintenance()">
                            <i class="fas fa-tools"></i><br>
                            <small>系统维护</small>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_css %}
<style>
.stat-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
}

.stat-content h3 {
    margin: 0;
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.stat-content p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.template-stats {
    max-height: 300px;
    overflow-y: auto;
}

.template-stat-item {
    display: flex;
    justify-content: between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
}

.template-stat-item:last-child {
    border-bottom: none;
}

.template-name {
    font-weight: 500;
    color: #333;
}

.template-usage {
    color: #666;
    font-size: 12px;
}

.usage-count {
    font-weight: bold;
    color: #007bff;
}

.metric-item {
    text-align: center;
    padding: 15px 0;
}

.metric-value {
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.metric-label {
    font-size: 12px;
    color: #666;
    margin-top: 5px;
}

.activity-feed {
    max-height: 400px;
    overflow-y: auto;
}

.activity-item {
    display: flex;
    align-items: flex-start;
    gap: 10px;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
    border-bottom: none;
}

.activity-icon {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: white;
    flex-shrink: 0;
}

.activity-content {
    flex-grow: 1;
}

.activity-title {
    font-weight: 500;
    color: #333;
    margin: 0;
    font-size: 14px;
}

.activity-description {
    color: #666;
    margin: 2px 0 0 0;
    font-size: 12px;
}

.activity-time {
    color: #999;
    font-size: 11px;
    white-space: nowrap;
}

.system-status .status-item {
    margin-bottom: 15px;
}

.system-status .status-item:last-child {
    margin-bottom: 0;
}

.progress {
    height: 6px;
}

.quick-actions .btn {
    height: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 5px;
}
</style>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// 图表实例
let charts = {};
let refreshInterval;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeAnalyticsDashboard();
});

// 初始化分析仪表板
function initializeAnalyticsDashboard() {
    // 加载初始数据
    loadDashboardData();
    
    // 初始化图表
    initializeCharts();
    
    // 设置自动刷新
    setupAutoRefresh();
    
    // 绑定事件
    bindEvents();
}

// 加载仪表板数据
function loadDashboardData() {
    fetch('/analytics/ajax/dashboard-data/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            updateDashboardStats(data.stats);
            updateCharts(data.charts);
            updateTemplateStats(data.template_stats);
            updatePerformanceMetrics(data.performance);
            updateActivityFeed(data.activities);
            updateSystemStatus(data.system_status);
        }
    })
    .catch(error => {
        console.error('加载仪表板数据失败:', error);
        CFS.utils.showNotification('加载数据失败', 'error');
    });
}

// 更新仪表板统计
function updateDashboardStats(stats) {
    document.getElementById('total-files').textContent = stats.total_files || 0;
    document.getElementById('total-tasks').textContent = stats.total_tasks || 0;
    document.getElementById('total-templates').textContent = stats.total_templates || 0;
    document.getElementById('storage-used').textContent = CFS.utils.formatFileSize(stats.storage_used || 0);
    
    // 更新趋势
    updateTrendIndicator('files-trend', stats.files_trend);
    updateTrendIndicator('tasks-trend', stats.tasks_trend);
    updateTrendIndicator('templates-trend', stats.templates_trend);
    updateTrendIndicator('storage-trend', stats.storage_trend);
}

// 更新趋势指示器
function updateTrendIndicator(elementId, trend) {
    const element = document.getElementById(elementId);
    const value = trend || 0;
    const isPositive = value >= 0;
    
    element.textContent = `${isPositive ? '+' : ''}${value}% 较昨日`;
    element.className = isPositive ? 'text-success' : 'text-danger';
}

// 初始化图表
function initializeCharts() {
    // 文件类型分布图
    const fileTypesCtx = document.getElementById('fileTypesChart').getContext('2d');
    charts.fileTypes = new Chart(fileTypesCtx, {
        type: 'doughnut',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: ['#007bff', '#28a745', '#ffc107', '#dc3545', '#6c757d']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    
    // 任务状态分布图
    const taskStatusCtx = document.getElementById('taskStatusChart').getContext('2d');
    charts.taskStatus = new Chart(taskStatusCtx, {
        type: 'pie',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: ['#28a745', '#ffc107', '#007bff', '#dc3545']
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
    
    // 趋势分析图
    const trendsCtx = document.getElementById('trendsChart').getContext('2d');
    charts.trends = new Chart(trendsCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [
                {
                    label: '文件上传',
                    data: [],
                    borderColor: '#007bff',
                    backgroundColor: 'rgba(0, 123, 255, 0.1)',
                    tension: 0.4
                },
                {
                    label: '任务处理',
                    data: [],
                    borderColor: '#28a745',
                    backgroundColor: 'rgba(40, 167, 69, 0.1)',
                    tension: 0.4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    position: 'top'
                }
            }
        }
    });
    
    // 性能指标图
    const performanceCtx = document.getElementById('performanceChart').getContext('2d');
    charts.performance = new Chart(performanceCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '响应时间 (ms)',
                data: [],
                borderColor: '#ffc107',
                backgroundColor: 'rgba(255, 193, 7, 0.1)',
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });
}

// 更新图表
function updateCharts(chartData) {
    // 更新文件类型分布图
    if (chartData.file_types) {
        charts.fileTypes.data.labels = chartData.file_types.labels;
        charts.fileTypes.data.datasets[0].data = chartData.file_types.data;
        charts.fileTypes.update();
    }
    
    // 更新任务状态分布图
    if (chartData.task_status) {
        charts.taskStatus.data.labels = chartData.task_status.labels;
        charts.taskStatus.data.datasets[0].data = chartData.task_status.data;
        charts.taskStatus.update();
    }
    
    // 更新趋势分析图
    if (chartData.trends) {
        charts.trends.data.labels = chartData.trends.labels;
        charts.trends.data.datasets[0].data = chartData.trends.files;
        charts.trends.data.datasets[1].data = chartData.trends.tasks;
        charts.trends.update();
    }
    
    // 更新性能指标图
    if (chartData.performance) {
        charts.performance.data.labels = chartData.performance.labels;
        charts.performance.data.datasets[0].data = chartData.performance.response_times;
        charts.performance.update();
    }
}

// 更新模板统计
function updateTemplateStats(templateStats) {
    const container = document.getElementById('template-stats');
    
    if (!templateStats || templateStats.length === 0) {
        container.innerHTML = '<p class="text-muted text-center">暂无模板使用数据</p>';
        return;
    }
    
    const html = templateStats.map(template => `
        <div class="template-stat-item">
            <div class="flex-grow-1">
                <div class="template-name">${template.name}</div>
                <div class="template-usage">最近使用: ${template.last_used || '从未'}</div>
            </div>
            <div class="text-end">
                <div class="usage-count">${template.usage_count}</div>
                <div class="template-usage">次使用</div>
            </div>
        </div>
    `).join('');
    
    container.innerHTML = html;
}

// 更新性能指标
function updatePerformanceMetrics(performance) {
    if (!performance) return;
    
    document.getElementById('avg-processing-time').textContent = 
        performance.avg_processing_time ? `${performance.avg_processing_time}ms` : '-';
    document.getElementById('success-rate').textContent = 
        performance.success_rate ? `${performance.success_rate}%` : '-';
    document.getElementById('queue-length').textContent = 
        performance.queue_length || 0;
    document.getElementById('active-workers').textContent = 
        performance.active_workers || 0;
}

// 更新活动动态
function updateActivityFeed(activities) {
    const container = document.getElementById('activity-feed');
    
    if (!activities || activities.length === 0) {
        container.innerHTML = '<p class="text-muted text-center">暂无活动记录</p>';
        return;
    }
    
    const html = activities.map(activity => {
        const iconClass = getActivityIcon(activity.type);
        const iconColor = getActivityColor(activity.type);
        
        return `
            <div class="activity-item">
                <div class="activity-icon bg-${iconColor}">
                    <i class="fas ${iconClass}"></i>
                </div>
                <div class="activity-content">
                    <div class="activity-title">${activity.title}</div>
                    <div class="activity-description">${activity.description}</div>
                </div>
                <div class="activity-time">
                    ${CFS.utils.formatDateTime(activity.timestamp)}
                </div>
            </div>
        `;
    }).join('');
    
    container.innerHTML = html;
}

// 获取活动图标
function getActivityIcon(type) {
    const icons = {
        'file_upload': 'fa-upload',
        'task_start': 'fa-play',
        'task_complete': 'fa-check',
        'task_error': 'fa-exclamation-triangle',
        'template_create': 'fa-plus',
        'template_update': 'fa-edit',
        'system': 'fa-cog'
    };
    return icons[type] || 'fa-info';
}

// 获取活动颜色
function getActivityColor(type) {
    const colors = {
        'file_upload': 'primary',
        'task_start': 'info',
        'task_complete': 'success',
        'task_error': 'danger',
        'template_create': 'success',
        'template_update': 'warning',
        'system': 'secondary'
    };
    return colors[type] || 'secondary';
}

// 更新系统状态
function updateSystemStatus(systemStatus) {
    if (!systemStatus) return;
    
    // CPU使用率
    if (systemStatus.cpu_usage !== undefined) {
        const cpuUsage = Math.round(systemStatus.cpu_usage);
        document.getElementById('cpu-usage').textContent = `${cpuUsage}%`;
        document.getElementById('cpu-progress').style.width = `${cpuUsage}%`;
        
        // 更新颜色
        const cpuElement = document.getElementById('cpu-usage');
        const cpuProgress = document.getElementById('cpu-progress');
        if (cpuUsage > 80) {
            cpuElement.className = 'badge bg-danger';
            cpuProgress.className = 'progress-bar bg-danger';
        } else if (cpuUsage > 60) {
            cpuElement.className = 'badge bg-warning';
            cpuProgress.className = 'progress-bar bg-warning';
        } else {
            cpuElement.className = 'badge bg-success';
            cpuProgress.className = 'progress-bar bg-success';
        }
    }
    
    // 内存使用率
    if (systemStatus.memory_usage !== undefined) {
        const memoryUsage = Math.round(systemStatus.memory_usage);
        document.getElementById('memory-usage').textContent = `${memoryUsage}%`;
        document.getElementById('memory-progress').style.width = `${memoryUsage}%`;
    }
    
    // 磁盘使用率
    if (systemStatus.disk_usage !== undefined) {
        const diskUsage = Math.round(systemStatus.disk_usage);
        document.getElementById('disk-usage').textContent = `${diskUsage}%`;
        document.getElementById('disk-progress').style.width = `${diskUsage}%`;
    }
    
    // 网络状态
    if (systemStatus.network_status !== undefined) {
        const networkElement = document.getElementById('network-status');
        if (systemStatus.network_status) {
            networkElement.textContent = '正常';
            networkElement.className = 'badge bg-success';
        } else {
            networkElement.textContent = '异常';
            networkElement.className = 'badge bg-danger';
        }
    }
    
    // 数据库状态
    if (systemStatus.db_status !== undefined) {
        const dbElement = document.getElementById('db-status');
        if (systemStatus.db_status) {
            dbElement.textContent = '正常';
            dbElement.className = 'badge bg-success';
        } else {
            dbElement.textContent = '异常';
            dbElement.className = 'badge bg-danger';
        }
    }
}

// 设置自动刷新
function setupAutoRefresh() {
    const autoRefreshCheckbox = document.getElementById('auto-refresh');
    
    function startAutoRefresh() {
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
        
        refreshInterval = setInterval(() => {
            if (autoRefreshCheckbox.checked) {
                loadDashboardData();
            }
        }, 30000); // 30秒刷新一次
    }
    
    autoRefreshCheckbox.addEventListener('change', function() {
        if (this.checked) {
            startAutoRefresh();
        } else {
            if (refreshInterval) {
                clearInterval(refreshInterval);
                refreshInterval = null;
            }
        }
    });
    
    // 初始启动
    if (autoRefreshCheckbox.checked) {
        startAutoRefresh();
    }
}

// 绑定事件
function bindEvents() {
    // 趋势周期变化
    document.getElementById('trend-period').addEventListener('change', updateTrendChart);
}

// 更新趋势图表
function updateTrendChart() {
    const period = document.getElementById('trend-period').value;
    
    fetch(`/analytics/ajax/trend-data/?period=${period}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            charts.trends.data.labels = data.labels;
            charts.trends.data.datasets[0].data = data.files;
            charts.trends.data.datasets[1].data = data.tasks;
            charts.trends.update();
        }
    })
    .catch(error => {
        console.error('更新趋势图表失败:', error);
    });
}

// 刷新图表
function refreshChart(chartType) {
    switch(chartType) {
        case 'fileTypes':
        case 'taskStatus':
        case 'trends':
            loadDashboardData();
            break;
        default:
            console.warn('未知的图表类型:', chartType);
    }
}

// 导出图表
function exportChart(chartType) {
    const chart = charts[chartType];
    if (!chart) {
        CFS.utils.showNotification('图表不存在', 'warning');
        return;
    }
    
    const url = chart.toBase64Image();
    const link = document.createElement('a');
    link.download = `${chartType}_chart.png`;
    link.href = url;
    link.click();
}

// 查看所有模板
function viewAllTemplates() {
    window.location.href = '/template-management/templates/';
}

// 查看系统日志
function viewSystemLogs() {
    window.location.href = '/analytics/logs/';
}

// 查看文件日志
function viewFileLogs() {
    window.location.href = '/analytics/file-logs/';
}

// 导出报告
function exportReport() {
    const format = prompt('请选择导出格式 (pdf/excel/csv):', 'pdf');
    if (!format) return;
    
    window.open(`/analytics/export/report/?format=${format}`);
}

// 定时报告
function scheduleReport() {
    // TODO: 实现定时报告功能
    showInfo('定时报告功能正在开发中，敬请期待');
}

// 自定义分析
function customAnalysis() {
    // TODO: 实现自定义分析功能
    showInfo('自定义分析功能正在开发中，敬请期待');
}

// 系统维护
function systemMaintenance() {
    // TODO: 实现系统维护功能
    showInfo('系统维护功能正在开发中，敬请期待');
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
});
</script>
{% endblock %}